package com.prawn.authority.controller;
import com.prawn.authority.utils.GlobalException;
import entity.Result;
import entity.StatusCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 统一异常处理类
 */
@ControllerAdvice
public class BaseExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result error(HttpServletRequest request, Exception e){
        if (e instanceof AccessDeniedException){
            return new Result(false, StatusCode.ACCESSERROR, "权限不足");
        }else if(e instanceof BadCredentialsException){
            return new Result(false, StatusCode.LOGINERROR, "密码不正确");
        }else if(e instanceof UsernameNotFoundException){
            return new Result(false, StatusCode.LOGINERROR, e.getMessage());
        } else if(e instanceof GlobalException){
            return ((GlobalException)e).getResult();
        }
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR, "执行出错");
    }
}
